package com.engine4cloud.tdf.admin.convert;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.engine4cloud.tdf.admin.api.dto.SysFileUploadRequestDTO;
import com.engine4cloud.tdf.admin.api.dto.SysFileUploadResultDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.TreeMap;

@Mapper
public interface SysFileConvert {
	SysFileConvert INSTANCE = Mappers.getMapper(SysFileConvert.class);

	default SysFileUploadResultDTO convert(SysFileUploadRequestDTO s, String originalName) {
		SysFileUploadResultDTO result = new SysFileUploadResultDTO();
		String fileName = DateUtil.format(LocalDateTime.now(), "YYYYMMDD") + IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(originalName);
		result.setBucketName(s.getBucketName());
		result.setFileName(s.isRename() ? fileName : (StringUtils.isEmpty(originalName) ? fileName : originalName));
		result.setName(originalName);
		result.setDir(s.getDir());
		result.setChildDir(s.getChildDir());
		convert(result);
		return result;
	}

	default void convert(SysFileUploadResultDTO result) {
		StringBuffer url = new StringBuffer("/admin/sys-file/oss/file?");
		Map<String, Object> bean = new TreeMap<>(BeanUtil.beanToMap(result, false, true));
		bean.remove("name");
		bean.forEach((k, v) -> {
			url.append(k + "=" + v + "&");
		});
		url.delete(url.length() - 1, url.length());
		result.setUrl(url.toString());
	}
}
